package com.css.fxfzypg.modules.resultupload.controller;

import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.service.PreAssessTaskService;
import com.css.fxfzypg.modules.resultupload.repository.entity.ResultMainEntity;
import com.css.fxfzypg.modules.resultupload.service.ResultTotalService;
import com.css.fxfzypg.util.PlatformPageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ClassUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: fxfzypg
 * @Author: lhl
 * @CreateDate: 2022/11/8 9:47
 */
@Slf4j
@RestController
@Validated
@RequestMapping("/result")
public class ResultTotalController {
    @Resource
    ResultTotalService resultTotalService;
    @Resource
    PreAssessTaskService preAssessTaskService;

    @GetMapping("/all")
    public RestResponse getAll(HttpServletRequest request,String taskId){
        RestResponse restResponse=null;
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize=Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            Map<String,Object> page = resultTotalService.getAll(taskId,curPage,pageSize);
            restResponse=RestResponse.succeed(page);
        }catch (Exception e){
            e.printStackTrace();
            restResponse=RestResponse.fail("查询失败!");
        }
        return restResponse;
    }
    @GetMapping("/allNoPage")
    public RestResponse allNoPage(HttpServletRequest request,String taskId){
        RestResponse restResponse=null;
        try {
            List<ResultMainEntity> list = resultTotalService.allNoPage(taskId);
            restResponse=RestResponse.succeed(list);
        }catch (Exception e){
            e.printStackTrace();
            restResponse=RestResponse.fail("查询失败!");
        }
        return restResponse;
    }


    @GetMapping("/allDetails")
    public RestResponse getAllDetails(@RequestParam String taskId){
        RestResponse restResponse=null;
        try {
            restResponse=resultTotalService.getAllDetails(taskId);
        }catch (Exception e){
            e.printStackTrace();
            restResponse=RestResponse.fail("查询失败!");
        }
        return restResponse;
    }

    @PostMapping("/updateAll")
    public RestResponse updateAll(@RequestBody List<ResultMainEntity> list){
        RestResponse restResponse=null;
        try {
            restResponse=resultTotalService.updateAll(list);
        }catch (Exception e){
            e.printStackTrace();
            restResponse=RestResponse.fail("修改失败!");
        }
        return restResponse;
    }

    @GetMapping("/details")
    public RestResponse getDetails(@RequestParam String taskId){
        RestResponse restResponse=null;
        try {
            restResponse=resultTotalService.getAllDetails(taskId);
        }catch (Exception e){
            e.printStackTrace();
            restResponse=RestResponse.fail("查询失败!");
        }
        return restResponse;
    }



    // 导出表内数据
    @PostMapping("/dataExport/{taskId}")
    public void exportExcel(@PathVariable String taskId, HttpServletResponse response) throws IOException {
        InputStream is = null;
        InputStream taIs = null;
        OutputStream os = null;
        XSSFWorkbook workbook = null;
        XSSFSheet sheet = null;
        try {
            PreAssessTaskEntity byId = preAssessTaskService.getById(taskId);
            String dateDir = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String excelUrl = "/usr/zhaoshuai/houduan/excel" + "/" + "预评估结果表头.xlsx";
//            String excelUrl = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "excel/" + "预评估结果表头.xlsx";
            List<ResultMainEntity> resultMainEntities = resultTotalService.exportExcel(taskId);
            File newFile = new File(excelUrl);
            is = Files.newInputStream(newFile.toPath()); // 将excel文件转为输入流

            workbook = new XSSFWorkbook(is); // 创建workbook
            // 获取第一个sheet
            sheet = workbook.getSheetAt(0);

            // 清空现有数据（从第3行开始）
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 2; i <= lastRowNum; i++) {
                XSSFRow row = sheet.getRow(i);
                if (row != null) {
                    sheet.removeRow(row);
                }
            }

            // 创建新行并写数据
            for (int m = 0; m < resultMainEntities.size(); m++) {
                ResultMainEntity entity = resultMainEntities.get(m);
                XSSFRow row = sheet.createRow(m + 2); // 从第3行开始写数据

                // 写入每一列的数据
                row.createCell(0).setCellValue(entity.getSort());
                row.createCell(1).setCellValue(entity.getLongitude());
                row.createCell(2).setCellValue(entity.getLatitude());
                row.createCell(3).setCellValue(entity.getMacroPosition());
                row.createCell(4).setCellValue(String.valueOf(entity.getMagnitude()));
                row.createCell(5).setCellValue(String.valueOf(entity.getDisasterArea()));
                row.createCell(6).setCellValue(String.valueOf(entity.getDisasterNum()));
                row.createCell(7).setCellValue(String.valueOf(entity.getDisasterGdp()));
                row.createCell(8).setCellValue(entity.getDeathTollBefore());
                row.createCell(9).setCellValue(entity.getDeathTollAfter());
                row.createCell(10).setCellValue(entity.getInjuredNumBefore());
                row.createCell(11).setCellValue(entity.getInjuredNumAfter());
                row.createCell(12).setCellValue(entity.getDisasterLossBefore());
                row.createCell(13).setCellValue(entity.getDisasterLossAfter());
                row.createCell(14).setCellValue(entity.getResettledNumBefore());
                row.createCell(15).setCellValue(entity.getResettledNumAfter());
                row.createCell(16).setCellValue(entity.getRescueForceBefore());
                row.createCell(17).setCellValue(entity.getRescueForceAfter());
                row.createCell(18).setCellValue(entity.getRescueForceZyBefore());
                row.createCell(19).setCellValue(entity.getRescueForceZyAfter());
                row.createCell(20).setCellValue(entity.getRescueForceMjBefore());
                row.createCell(21).setCellValue(entity.getRescueForceMjAfter());
                row.createCell(22).setCellValue(entity.getRescueForceQtBefore());
                row.createCell(23).setCellValue(entity.getRescueForceQtAfter());
                row.createCell(24).setCellValue(entity.getTentNumBefore());
                row.createCell(25).setCellValue(entity.getTentNumAfter());
                row.createCell(26).setCellValue(entity.getStretcherNumBefore());
                row.createCell(27).setCellValue(entity.getStretcherNumAfter());
                row.createCell(28).setCellValue(entity.getQuiltsNumBefore());
                row.createCell(29).setCellValue(entity.getQuiltsNumAfter());
                row.createCell(30).setCellValue(entity.getFoodsNumBefore());
                row.createCell(31).setCellValue(entity.getFoodsNumAfter());
                row.createCell(32).setCellValue(entity.getWaterNumBefore());
                row.createCell(33).setCellValue(entity.getWaterNumAfter());
                row.createCell(34).setCellValue(entity.getBathroomNumBefore());
                row.createCell(35).setCellValue(entity.getBathroomNumAfter());
                row.createCell(36).setCellValue(entity.getShowersNumBefore());
                row.createCell(37).setCellValue(entity.getShowersNumAfter());
                row.createCell(38).setCellValue(entity.getMedicalMattersBefore());
                row.createCell(39).setCellValue(entity.getMedicalMattersAfter());
                row.createCell(40).setCellValue(entity.getMedicalNumBefore());
                row.createCell(41).setCellValue(entity.getMedicalNumAfter());
                row.createCell(42).setCellValue(entity.getNurseNumBefore());
                row.createCell(43).setCellValue(entity.getNurseNumAfter());
                row.createCell(44).setCellValue(entity.getPsychologistBefore());
                row.createCell(45).setCellValue(entity.getPsychologistAfter());
                row.createCell(46).setCellValue(entity.getSickroomNumBefore());
                row.createCell(47).setCellValue(entity.getSickroomNumAfter());
                row.createCell(48).setCellValue(entity.getSickbedNumBefore());
                row.createCell(49).setCellValue(entity.getSickbedNumAfter());
                row.createCell(50).setCellValue(entity.getPlasmaNumBefore());
                row.createCell(51).setCellValue(entity.getPlasmaNumAfter());
            }

            // 保存工作簿到输出流
            try (FileOutputStream fos = new FileOutputStream(newFile)) {
                workbook.write(fos);
            }

            // 设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=" + byId.getTaskName() + dateDir + ".xlsx");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Method", "POST,GET");

            // 读取文件并写入响应输出流
            os = response.getOutputStream();
            taIs = Files.newInputStream(newFile.toPath()); // 将excel文件转为输入流
            int flag;
            while ((flag = taIs.read()) != -1) {
                os.write(flag);
            }
        } catch (Exception e) {
            log.error("导出失败:" + e.getMessage(),e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (taIs != null) {
                    taIs.close();
                }
                if (os != null) {
                    os.flush();
                    os.close();
                }
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

//    public void exportExcel(@PathVariable String taskId, HttpServletResponse response) throws IOException {
//        InputStream is = null;
//        InputStream taIs = null;
//        OutputStream os = null;
//        XSSFWorkbook workbook = null;
//        XSSFSheet sheet = null;
//        try {
//            PreAssessTaskEntity byId = preAssessTaskService.getById(taskId);
//            String dateDir = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
//            //String excelUrl = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "excel/" + "预评估结果表头.xlsx";
//            String excelUrl = "/usr/zhaoshuai/houduan/excel" + "/" + "预评估结果表头.xlsx";
//            List<ResultMainEntity> resultMainEntities = resultTotalService.exportExcel(taskId);
//            //   FileUtil.exportExcel(resultMainEntities, "预评估任务结果表", "sheet", ResultMainEntity.class, byId.getTaskName()+dateDir, response);
//            File newFile = new File(excelUrl);
//            is = Files.newInputStream(newFile.toPath());// 将excel文件转为输入流
//
//            workbook = new XSSFWorkbook(is);// 创建workbook
//            // 获取第一个sheet
//            sheet = workbook.getSheetAt(0);
//            sheet.shiftRows(2,99999,498);
//                // 写数据
//                FileOutputStream fos = new FileOutputStream(newFile);
//
//                XSSFRow row = sheet.getRow(2);
//                if (row == null) {
//                    row = sheet.createRow(2);
//                }
//                XSSFCell cell = row.getCell(0);
//                if (cell == null) {
//                    cell = row.createCell(0);
//                }
//                for (int m = 0; m < resultMainEntities.size(); m++) {
//                    ResultMainEntity entity = resultMainEntities.get(m);
//                    row = sheet.createRow(m + 2);
//                    // id
//                    cell = row.createCell(0);
//                    cell.setCellValue(entity.getSort());
//                    // 经度
//                    cell = row.createCell(1);
//                    cell.setCellValue(entity.getLongitude());
//                    // 纬度
//                    cell = row.createCell(2);
//                    cell.setCellValue(entity.getLatitude());
//
//                    cell = row.createCell(3);
//                    cell.setCellValue(entity.getMacroPosition());
//
//                    cell = row.createCell(4);
//                    cell.setCellValue(String.valueOf(entity.getMagnitude()));
//
//                    cell = row.createCell(5);
//                    cell.setCellValue(String.valueOf(entity.getDisasterArea()));
//
//                    cell = row.createCell(6);
//                    cell.setCellValue(String.valueOf(entity.getDisasterNum()));
//
//                    cell = row.createCell(7);
//                    cell.setCellValue(String.valueOf(entity.getDisasterGdp()));
//
//                    cell = row.createCell(8);
//                    cell.setCellValue(entity.getDeathTollBefore());
//                    cell = row.createCell(9);
//                    cell.setCellValue(entity.getDeathTollAfter());
//
//                    cell = row.createCell(10);
//                    cell.setCellValue(entity.getInjuredNumBefore());
//                    cell = row.createCell(11);
//                    cell.setCellValue(entity.getInjuredNumAfter());
//
//                    cell = row.createCell(12);
//                    cell.setCellValue(entity.getDisasterLossBefore());
//                    cell = row.createCell(13);
//                    cell.setCellValue(entity.getDisasterLossAfter());
//
//                    cell = row.createCell(14);
//                    cell.setCellValue(entity.getResettledNumBefore());
//                    cell = row.createCell(15);
//                    cell.setCellValue(entity.getResettledNumAfter());
//
//                    cell = row.createCell(16);
//                    cell.setCellValue(entity.getRescueForceBefore());
//                    cell = row.createCell(17);
//                    cell.setCellValue(entity.getRescueForceAfter());
//
//                    cell = row.createCell(18);
//                    cell.setCellValue(entity.getRescueForceZyBefore());
//                    cell = row.createCell(19);
//                    cell.setCellValue(entity.getRescueForceZyAfter());
//
//                    cell = row.createCell(20);
//                    cell.setCellValue(entity.getRescueForceMjBefore());
//                    cell = row.createCell(21);
//                    cell.setCellValue(entity.getRescueForceMjAfter());
//
//                    cell = row.createCell(22);
//                    cell.setCellValue(entity.getRescueForceQtBefore());
//                    cell = row.createCell(23);
//                    cell.setCellValue(entity.getRescueForceQtAfter());
//
//                    cell = row.createCell(24);
//                    cell.setCellValue(entity.getTentNumBefore());
//                    cell = row.createCell(25);
//                    cell.setCellValue(entity.getTentNumAfter());
//
//                    cell = row.createCell(26);
//                    cell.setCellValue(entity.getStretcherNumBefore());
//                    cell = row.createCell(27);
//                    cell.setCellValue(entity.getStretcherNumAfter());
//
//                    cell = row.createCell(28);
//                    cell.setCellValue(entity.getQuiltsNumBefore());
//                    cell = row.createCell(29);
//                    cell.setCellValue(entity.getQuiltsNumAfter());
//
//                    cell = row.createCell(30);
//                    cell.setCellValue(entity.getFoodsNumBefore());
//                    cell = row.createCell(31);
//                    cell.setCellValue(entity.getFoodsNumAfter());
//
//                    cell = row.createCell(32);
//                    cell.setCellValue(entity.getWaterNumBefore());
//                    cell = row.createCell(33);
//                    cell.setCellValue(entity.getWaterNumAfter());
//
//                    cell = row.createCell(34);
//                    cell.setCellValue(entity.getBathroomNumBefore());
//                    cell = row.createCell(35);
//                    cell.setCellValue(entity.getBathroomNumAfter());
//
//                    cell = row.createCell(36);
//                    cell.setCellValue(entity.getShowersNumBefore());
//                    cell = row.createCell(37);
//                    cell.setCellValue(entity.getShowersNumAfter());
//
//                    cell = row.createCell(38);
//                    cell.setCellValue(entity.getMedicalMattersBefore());
//                    cell = row.createCell(39);
//                    cell.setCellValue(entity.getMedicalMattersAfter());
//
//
//                    cell = row.createCell(40);
//                    cell.setCellValue(entity.getMedicalNumBefore());
//                    cell = row.createCell(41);
//                    cell.setCellValue(entity.getMedicalNumAfter());
//
//                    cell = row.createCell(42);
//                    cell.setCellValue(entity.getNurseNumBefore());
//                    cell = row.createCell(43);
//                    cell.setCellValue(entity.getNurseNumAfter());
//
//                    cell = row.createCell(44);
//                    cell.setCellValue(entity.getPsychologistBefore());
//                    cell = row.createCell(45);
//                    cell.setCellValue(entity.getPsychologistAfter());
//
//                    cell = row.createCell(46);
//                    cell.setCellValue(entity.getSickroomNumBefore());
//                    cell = row.createCell(47);
//                    cell.setCellValue(entity.getSickroomNumAfter());
//
//                    cell = row.createCell(48);
//                    cell.setCellValue(entity.getSickbedNumBefore());
//                    cell = row.createCell(49);
//                    cell.setCellValue(entity.getSickbedNumAfter());
//
//                    cell = row.createCell(50);
//                    cell.setCellValue(entity.getPlasmaNumBefore());
//                    cell = row.createCell(51);
//                    cell.setCellValue(entity.getPlasmaNumAfter());
//
//                }
//                workbook.write(fos);
//                fos.flush();
//                fos.close();
//            response.setHeader("Content-Disposition", "attchment;filename=" + byId.getTaskName()+dateDir+".xlsx");
//            response.setHeader("Access-Control-Allow-Origin", "*");
//            response.setHeader("Access-Control-Allow-Method", "POST,GET");
//          //  is = new FileInputStream(new File(name));
//
//            // PrintWrite pw=response.getWriter();  或
//
//            //String taUrl = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "excel/" + "预评估结果表头.xlsx";
//            String taUrl = "/usr/zhaoshuai/houduan/excel" + "/" + "预评估结果表头.xlsx";
//            File taNewFile = new File(taUrl);
//            taIs = Files.newInputStream(taNewFile.toPath());// 将excel文件转为输入流
//            os = response.getOutputStream();
//            int flag = 0;
//            while ((flag = taIs.read()) != -1) {
//                os.write(flag);
//            }
//        } catch (Exception e) {
//            log.error("导出失败:" + e.getMessage());
//        }finally{
//            try{
//                if(is != null){
//                    is.close();
//                }
//                if(os != null){
//                    os.flush();
//                    os.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }


}
